// pages/Welcome/Welcome.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { getToken , codeLogin , queryWechatPhone , getCode , Login } from '../../api/login';
import { getUser } from '../../api/user';
import { queryPetStoreManagerConfig } from '../../api/merchant';
import { ACCESS_TOKEN } from '../../utils/types';
import { isNumberOr_Letter } from '../../utils/util';
const regeneratorRuntime = require('../../common/runtime');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    parentUserId: '', // 推荐人ID
    assetsAddress: assetsAddress,
    brandName: app.globalData.global.brandName,
    show: false,
    showPhoneCode: false,
    code: '', // 验证码
    num: 60,
    params: '',
    pathName: '',
    showPrivacyAuthor: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options,'options')
    if(options && options.scene){
      const scene = decodeURIComponent(options.scene)
      var arr = scene.split('---');
      console.log(scene,'scene')
      this.setData({
        parentUserId: arr.length > 1 ? arr[0] : scene,
        params: arr.length > 1 ? arr[1] : '',
        pathName: arr.length > 2 ? arr[2] : '',
      })
      wx.setStorageSync('parentUserId', arr.length > 1 ? arr[0] : scene)
      wx.setStorageSync('params', arr.length > 1 ? arr[1] : '')
      wx.setStorageSync('pathName', arr.length > 2 ? arr[2] : '')
    }
    this.login(); 
    // this.ceshiLogin();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // // 登录
  login(){
    // 获取服务器token
    getToken().then(res => {
      let _this = this;
      if(res.success){
        wx.setStorageSync(ACCESS_TOKEN, res[ACCESS_TOKEN]);
        // 登录
        wx.login({
          success: logRes => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            console.log(logRes,'logRes')
            if (logRes.code) {
              codeLogin(logRes.code,_this.data.parentUserId)
              .then(async rres => {
                console.log(rres,'第一次登录返回的rres')
                if(rres.success){
                  wx.setStorageSync(ACCESS_TOKEN, rres.access_token);
                  wx.setStorageSync('expires_in', rres.expires_in);
                  getUser({})
                  .then(async user => {
                    if(user.success){
                      wx.setStorageSync('userId', user.data.userId)
                      wx.setStorageSync('phone', user.data.phone)
                      var managerList = await _this._queryPetStoreManagerConfig();
                      if(managerList.length > 0){
                        wx.navigateTo({
                          url: '/pages/Manager/ManagerHome/ManagerHome',
                        })
                      }else{
                        wx.switchTab({
                          url: '/pages/Tabbar/Home/Home',
                        });
                      }
                    }
                  })
                            
                }else{
                  wx.showToast({
                    title: rres.errMessage,
                    icon: 'none',
                  })
                }
              })
            } else {
              wx.showToast({
                title: logRes.errMsg,
                icon: 'none',
              })
            }
          },
            fail:function(err){
              console.log(err,'err')
            }
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
    ceshiLogin(){
      // 获取服务器token
      getToken().then(res => {
          let _this = this;
          if(res.success){
              wx.setStorageSync(ACCESS_TOKEN, res[ACCESS_TOKEN]);
              // 登录
              wx.login({
                  success: async logRes => {
                  // 发送 res.code 到后台换取 openId, sessionKey, unionId
                  console.log(logRes,'logRes')
                  if (logRes.code) {
                    Login({account: '18520149705', password: 'a123456'})
                      .then(async rres => {
                      console.log(rres,'第一次登录返回的rres')
                      if(rres.success){
                        wx.setStorageSync(ACCESS_TOKEN, rres.access_token);
                        wx.setStorageSync('expires_in', rres.expires_in);
                        getUser({})
                        .then(async user => {
                          if(user.success){
                            wx.setStorageSync('userId', user.data.userId)
                            wx.setStorageSync('phone', user.data.phone)
                            var managerList = await _this._queryPetStoreManagerConfig();
                            if(managerList.length > 0){
                              wx.navigateTo({
                                url: '/pages/Manager/ManagerHome/ManagerHome',
                              })
                            }else{
                              wx.switchTab({
                                url: '/pages/Tabbar/Home/Home',
                              });
                            }
                          }
                        })
                          // var managerList = await _this._queryPetStoreManagerConfig();
                          // if(managerList.length == 0){
                          //   wx.navigateTo({
                          //     url: '/pages/Manager/ManagerHome/ManagerHome',
                          //   })
                          // }else{
                          //   wx.switchTab({
                          //     url: '/pages/Tabbar/Home/Home',
                          //   });
                          // }
                      }else{
                          wx.showToast({
                          title: rres.errMessage,
                          icon: 'none',
                          })
                      }
                      })
                  } else {
                      wx.showToast({
                      title: logRes.errMsg,
                      icon: 'none',
                      })
                  }
                  },
              })
          }else{
              wx.showToast({
                  title: res.errMessage,
                  icon: 'none'
              })
          }
      })
    },
  // 获取当前用户是否是宠物门店管理员
  _queryPetStoreManagerConfig(){
    let _this = this
    return new Promise((resolve,reject) => {
      queryPetStoreManagerConfig({})
      .then(res => {
        if(res.success){
          resolve(res.data.content);
        }else{
          reject(res.errMessage)
        }
      })
    })
  },
})